import { createRouter, createWebHistory } from 'vue-router';
import { authService } from '@/service/AuthService';
import Index from '@/views/Index.vue';

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        { path: '/', name: 'index', component: Index, meta: { requiresAuth: true } },
        { path: '/main', name: "main", component: () => import('@/views/Main.vue'), meta: { requiresAuth: true } },
        { path: '/login', name: "login", component: () => import('@/views/Login.vue') },
        { path: '/businessInfo', name: "business-info", component: () => import('@/views/BusinessInfo.vue'), meta: { requiresAuth: true } }, // 修改路径为小写
        { path: '/businessList', name: "businessList", component: () => import('@/views/BusinessList.vue'), meta: { requiresAuth: true } },
        { path: '/orders', name: "orders", component: () => import('@/views/Orders.vue'), meta: { requiresAuth: true } },
        { path: '/payment', name: "payment", component: () => import('@/views/Payment.vue'), meta: { requiresAuth: true } },
        { path: '/register', name: "register", component: () => import('@/views/Register.vue') },
        { path: '/index', name: "Index", component: Index, meta: { requiresAuth: true } },
        { path: "/", redirect: "/main" } // 确保重定向规则不会覆盖 /businessInfo
    ],
});

router.beforeEach((to, from) => {
    authService.checkLoginStatus(); // 检查登录状态
    console.log('路由守卫检查:', to.path, authService.isLoggedIn); // 调试信息

    if (to.meta.requiresAuth && !authService.isLoggedIn) {
        return { name: "login" }; // 如果未登录，重定向到登录页面
    }
});

export default router;